package com.fzc.rhinooffice.module.office;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.JsonReader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fzc.rhinooffice.R;
import com.fzc.rhinooffice.common.RemoteInvoke;
import com.fzc.rhinooffice.common.utils.JsonUtil;
import com.fzc.rhinooffice.common.view.PullRefreshListView;
import com.fzc.rhinooffice.module.BaseActivity;
import com.fzc.rhinooffice.module.CommonAdapter;
import com.fzc.rhinooffice.module.ViewHolder;
import com.fzc.rhinooffice.module.entity.Email;
import com.fzc.rhinooffice.module.workbench.EmailDetailActivity;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.StringReader;
import java.util.List;

@SuppressLint("NewApi")
@ContentView(R.layout.activity_mail_list)
public class EmailListActivity extends BaseActivity implements OnItemClickListener {

    @ViewInject(R.id.iv_back)
    private ImageView iv_back;

    @ViewInject(R.id.tv_title)
    private TextView tv_title;

    @ViewInject(R.id.tv_filter)
    private TextView tv_filter;


    @ViewInject(R.id.srl_refresh_view)
    private SwipeRefreshLayout srl_refresh_view;

    @ViewInject(R.id.lv_mails)
    private PullRefreshListView lv_mails;

    private CommonAdapter<Email> commonAdapter;

    private List<Email> emailList;

    private Intent mIntent;

    private int page = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        initUI();
    }

    @SuppressLint("ResourceAsColor")
    private void initUI() {
        tv_title.setText("邮件");
        lv_mails.setOnItemClickListener(this);
        srl_refresh_view.setColorSchemeResources(R.color.swipe_color_1, R.color.swipe_color_2, R.color.swipe_color_3, R.color.swipe_color_4);
        srl_refresh_view.setSize(SwipeRefreshLayout.LARGE);
        srl_refresh_view.setProgressViewEndTarget(true, 200);

        //加载更多的监听
        lv_mails.setPullLoadMoreListener(new PullRefreshListView.PullLoadMoreListener() {
            @Override
            public void loadMore() {//加载更多
                page++;
                getEmails();
            }
        });
        //下拉刷新还是官方的那个
        srl_refresh_view.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getEmails();
            }
        });
        //自动下拉，模拟用户手势实现
        lv_mails.startAutoRefresh(srl_refresh_view);//自动下拉

    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            srl_refresh_view.setRefreshing(false);
            //加载完毕告诉listView结束了
            lv_mails.endRefresh();//结束加载

            switch (msg.what) {
                case 2:
                    JSONObject jsonObject = (JSONObject) msg.obj;
                    if (jsonObject != null) {
                        try {
                            if (jsonObject.getString("record") != null
                                    && !"".equals(jsonObject.getString("record"))) {

                                if (emailList == null || page == 1) {
                                    emailList = JsonUtil.analysis_emails(new JsonReader(new StringReader(jsonObject.optString("record"))));
                                } else {
                                    emailList.addAll(JsonUtil.analysis_emails(new JsonReader(new StringReader(jsonObject.optString("record")))));
                                }
                                if (emailList != null && emailList.size() != 0) {
                                    initAdapter();
                                } else {
                                    Toast.makeText(EmailListActivity.this, "暂无可读邮件",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(EmailListActivity.this, "未知错误",
                                Toast.LENGTH_SHORT).show();
                    }

                    break;

                case -2:
                    Toast.makeText(EmailListActivity.this, "邮件列表加载失败！",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }


    };

    private void getEmails() {
        RemoteInvoke.email(mHandler, "2010-04-30", "2016-05-01", "", page);
    }

    private void initAdapter() {

        if (commonAdapter == null) {
            commonAdapter = new CommonAdapter<Email>(this, emailList, R.layout.email_list_item) {

                @Override
                public void convert(ViewHolder holder, Email item) {

                    holder.setText(R.id.tv_email_from_name, item.from_name);
                    holder.setText(R.id.tv_email_subject, item.subject);
                    holder.setText(R.id.tv_email_send_time, item.send_time);
                    holder.setText(R.id.tv_email_content, item.content + "\n…");

                    if (item.is_new.equals("0")) {
                        holder.setViewVisibility(R.id.iv_isnew, View.VISIBLE);
                    } else {
                        holder.setViewVisibility(R.id.iv_isnew, View.INVISIBLE);
                    }

                }
            };
            lv_mails.setAdapter(commonAdapter);

        } else {
            commonAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        //点击了的要把item。isnew改为1
        Email email = emailList.get(position);
        email.is_new = "1";
        initAdapter();

        mIntent = new Intent(this, EmailDetailActivity.class);
        mIntent.putExtra("email_id", emailList.get(position).email_id);
        //mIntent.putExtra("email_id", "16");	//测试
        startActivity(mIntent);

    }


    @OnClick({R.id.iv_back, R.id.tv_title})
    private void OpenDL(View v) {
        super.back();
    }


}
